package com.ogawa.health.code.controller;

import com.alibaba.fastjson.JSON;
import com.ogawa.health.code.entity.OrderEntity;
import com.ogawa.health.code.service.GeneratorService;
import com.ogawa.health.code.utils.PageUtils;
import com.ogawa.health.code.utils.Query;
import com.ogawa.health.code.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import zyz.framework.controller.BaseController;
import zyz.framework.dao.query.QueryItem;
import zyz.framework.dao.query.Where;
import zyz.framework.entity.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年12月19日 下午9:12:58
 */
@Controller
@RequestMapping("/sys/generator")
public class GeneratorController extends BaseController {
    @Autowired
    private GeneratorService generatorService;

    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<Map<String, Object>> list = generatorService.queryList(query);
        int total = generatorService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    @ResponseBody
    public R code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] tableNames = new String[]{};
        String tables = request.getParameter("tables");
        tableNames = JSON.parseArray(tables).toArray(tableNames);
        generatorService.generatorCode(tableNames);
        return R.ok("生成成功");
    }

    /**
     * 生成代码
     */
    @RequestMapping("/test")
    @ResponseBody
    public R test(@RequestParam Map request) throws Exception {
        QueryItem queryItem = new QueryItem();
        queryItem.setFields("sum(orderPrice) orderPrice");
        OrderEntity data = (OrderEntity) this.getOne(queryItem, OrderEntity.class);
        queryItem=new QueryItem();
        queryItem.setWhere(Where.eq("payStatus","0"));
        List<Map> list= (List<Map>) this.getList(queryItem,OrderEntity.class,Map.class);
        queryItem.setPage(1);
        queryItem.setLimit(10);
        Page<Map> page= (Page<Map>) this.getPage(queryItem,OrderEntity.class,Map.class);
        return R.ok().put("data", data);
    }

}
